package com.zzh.framework.protocol.http;

import com.alibaba.fastjson.JSONObject;
import com.zzh.framework.Invocation;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

/**
 * @author：zhangzhanheng
 * @createTime: 2021/8/3  5:52 下午
 * @desc: http发送类
 * @version: 1.0.0
 **/
public class HttpClient {

    public String send(String hostname, Integer port, Invocation invocation)  {
        HttpRequest http = null;
        try {
            http = HttpRequest.newBuilder()
                    .uri(new URI("http", null, hostname, port, "/", null, null))
                    .POST(HttpRequest.BodyPublishers.ofString(JSONObject.toJSONString(invocation)))
                    .build();
            java.net.http.HttpClient client = java.net.http.HttpClient.newHttpClient();
            HttpResponse<String> response = client.send(http,HttpResponse.BodyHandlers.ofString());
            String result = response.body();
            return result;
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return null;

    }
}
